'''
FilePath: \hart\test\pkg\common.py
Author: shenghao.xu
Date: 2023-03-15 10:17:55
LastModifiedBy: shenghao.xu
LastEditTime: 2023-09-20 15:36:00
Descripttion:
'''
from ctypes import *
import os
import struct
import sys


def print_hex_data_space(bytes, uppercase=False):
    l = ['{:02x} '.format(int(i)) for i in bytes]
    if uppercase:
        l = [i.upper() for i in l]
    print("".join(l))
    pass


def print_hex_space(bytes):
    l = ['0x{:02x} '.format(int(i)) for i in bytes]
    print("".join(l))
    pass


# 十六进制打印
def print_hex(bytes):
    l = [hex(int(i)) for i in bytes]
    print("".join(l))
    pass


# 数组异或操作
def xor(bytes):
    result = 0
    for i in bytes:
        result ^= i
    return result


# bytearray 转 ctypes
def bytes_to_ctypes(bytes):
    return (c_ubyte * len(bytes))(*bytes)


# 字符串转assic码数组
def str_to_ascii(str):
    return [ord(i) for i in str]

# 字符串转assic-6码数组
def encode_ascii_6(input, input_length, output):
    adjusted_input = [0x20]*input_length
    i = 0

    for i in range(input_length):
        if input[i] == 0x00:
            adjusted_input[i] = 0x20
            continue

        adjusted_input[i] = input[i] - 0x40 if input[i] >= 0x40 else input[i]

    acs8_len = i + 1
    acs6_len = acs8_len * 6 // 8

    for i in range(acs6_len):
        pos = i * 8 // 6
        val = adjusted_input[pos] & 0x3f
        valNext = (adjusted_input[pos + 1] & 0x3f) if pos + 1 < acs8_len else 0x20
        newVal = 0
        if i % 3 == 0:
            newVal = val << 2
            newVal += valNext >> 4
        elif i % 3 == 1:
            newVal = val << 4
            newVal += valNext >> 2
        elif i % 3 == 2:
            newVal = val << 6
            newVal += valNext
        output[i] = newVal


# assic码数组转字符串
def ascii_to_str(ascii):
    # ascii 遇到00 截断
    if 0 in ascii:
        ascii = ascii[:ascii.index(0)]
    return ''.join([chr(i) for i in ascii])


# 数组B的值复制到数组A，从数组A的第offset个元素开始
def copy_to_array(A, B, offset):
    for i in range(len(B)):
        A[offset + i] = B[i]
    pass


# 将bytes转换为float32
def bytes2float32slice(bytes):
    x = []
    for i in range(int(len(bytes) / 4)):
        data = bytes[i * 4: (i * 4) + 4]
        a = struct.unpack('f', data)
        x.append(float(a[0]))
    return x

def convert_time(t):
    t = (t / 32)
    ms = t % 1000
    t = t / 1000
    h = t / 3600
    m = (t - (h) * 3600) / 60
    s = t - (h) * 3600 - (m) * 60
    return h,m,s

def convert_timestrap(h,m,s,ms):
    t = (h * 3600 + m * 60 + s) * 1000 + ms
    t = (t) * 32
    return t

class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, 'w')

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._original_stdout
